package com.vcs.frm.dao.mappers;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import com.vcs.frm.domain.User;
import com.vcs.frm.domain.UserRoles;

public class UserResultSetExtractor implements ResultSetExtractor<User> {

	@Override
	public User extractData(ResultSet rs) throws SQLException,
			DataAccessException {

		User user = new User();
		while (rs.next()) {

			user.setUserId(rs.getInt("USER_ID"));
			user.setUsername(rs.getString("USERNAME"));
			user.setPassword(rs.getString("PASSWORD"));
			user.setEnabled(rs.getString("ENABLED"));

			// process user roles
			// int userRoleId = rs.getInt("USER_ROLE_ID");
			do {
				if (rs.getInt("USER_ROLE_ID") > 0) {
					UserRoles roles = new UserRoles();
					roles.setUserRoleId(rs.getInt("USER_ROLE_ID"));
					roles.setUserId(rs.getInt("USER_ID"));
					roles.setAuthority(rs.getString("AUTHORITY"));
					user.getUserRoles().add(roles);
				}
			}while (rs.next());

		}

		return user;
	}

}
